package com.thprojects.myphotomemories.view;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.thprojects.myphotomemories.R;
import com.thprojects.myphotomemories.controller.FSController;
import com.thprojects.myphotomemories.controller.GuiController;
import com.thprojects.myphotomemories.model.Photo;
import com.thprojects.myphotomemories.view.components.ColorAdapter;
import com.thprojects.myphotomemories.view.components.DrawableImageView;
import com.thprojects.myphotomemories.view.components.OnDrawListener;

import exception.PhotoSourceNotFoundException;
import exception.SDNotReadyException;

public class DrawPhotoView extends Activity{
	
	FSController mFSController;
	GridView mPalette;
	DrawableImageView mImage;
	Photo mPhoto;
	MenuItem mUndo, mClear, mShowPalette;
	ImageView mChosenColor;
	LinearLayout mPaletteContainer;
	boolean isPaletteOpen;
	Bitmap mImageBitmap;

	
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.photo_draw);
	    
	    Intent i = getIntent();
        mPhoto = (Photo) i.getParcelableExtra("photo");

        mFSController = FSController.getFSController(this);
        
        mPaletteContainer = (LinearLayout)findViewById(R.id.palette_container);
        mChosenColor = (ImageView) findViewById(R.id.chosen_color);
        
	    mPalette = (GridView) findViewById(R.id.palette_grid);
	    mPalette.setAdapter(new ColorAdapter(this));

	    mPalette.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	        	if (!isPaletteOpen) return;
	        	mImage.setColor((Integer) mPalette.getItemAtPosition(position));
	        	mChosenColor.setBackgroundColor((Integer) mPalette.getItemAtPosition(position));
	        }
	    });
	    mPalette.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (isPaletteOpen){
					hidePalette();
					return false;
				}
				else{
					event.setLocation(event.getX()+mPalette.getLeft(), event.getY());
					mImage.dispatchTouchEvent(event);
					event.setLocation(event.getX()-mPalette.getLeft(), event.getY());
					return false;
				}
			}
		});
	    
	    try {
			mImageBitmap = mFSController.decodeSampledBitmap(mPhoto.getPath(), 500, 500);
		} catch (PhotoSourceNotFoundException e) {
			GuiController.showError(this, e.getMessage());
		} catch (SDNotReadyException e) {
			GuiController.showError(this, e.getMessage());
		}
	    
	    mImage = (DrawableImageView) findViewById(R.id.photo_preview);
	    mImage.setImageBitmap(mImageBitmap);
	    
	    mImage.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {       
            public void onGlobalLayout() {
             	Rect r = getBitmapRect();
        		Log.d("MPM", "r.w="+r.width()+", r.h="+r.height());
                mImage.setBoundingRect(r);
                Log.d("MPM", "i.w="+mImage.getWidth()+", i.h="+mImage.getHeight());
            }
	    });
	    
	    mImage.setOnDrawListener(new OnDrawListener() {
			public void OnDraw() {
				if (!mImage.isClean()){
					if (mUndo!= null && mClear!= null){
						mUndo.setEnabled(true);
						mClear.setEnabled(true);
					}
					
				}
			}
		});

	    
	    //buttons
	    Button cancelAlbumBtt = (Button)findViewById(R.id.cancel_draw);
	    cancelAlbumBtt.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	    
	    Button saveAlbumBtt = (Button)findViewById(R.id.save_draw);
	    saveAlbumBtt.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				saveImage();
				finish();
			}
		});
	    
	    mChosenColor.setBackgroundColor(Color.rgb(255, 0, 0));
	    openPalette();
	}
	
	protected void onSaveInstanceState(Bundle outState){
		super.onSaveInstanceState(outState);
		mImage.save(outState);
	}
	
	protected void onRestoreInstanceState(Bundle savedState){
		super.onSaveInstanceState(savedState);
		mImage.restore(savedState); 
		mChosenColor.setBackgroundColor(mImage.getColor());
	}
	
	private Rect getBitmapRect(){
		double bitmapRatio = ((double) mImageBitmap.getWidth())/ mImageBitmap.getHeight();
		double imageViewRatio = ((double) mImage.getWidth())/ mImage.getHeight();
		int drawLeft=0, drawTop=0, drawWidth=0, drawHeight=0;

		if(bitmapRatio > imageViewRatio)
		{
		  drawLeft = 0;
		  drawWidth = mImage.getWidth();
		  drawHeight = (int) ((mImage.getWidth()*mImageBitmap.getHeight())/mImageBitmap.getWidth());
		  drawTop = (mImage.getHeight() - drawHeight)/2;
		}
		else
		{
		  drawTop = 0;
		  drawWidth = (int) ((mImage.getHeight()*mImageBitmap.getWidth())/mImageBitmap.getHeight());
		  drawHeight = mImage.getHeight();
		  drawLeft = (mImage.getWidth() - drawWidth)/2;
		}
		
		return new Rect(drawLeft, drawTop, drawLeft+drawWidth, drawTop+drawHeight);
	}
	
	
	private void closePalette(){
		Animation a = AnimationUtils.loadAnimation(this, R.anim.shrink);
		mPaletteContainer.startAnimation(a);
		a.setAnimationListener(new AnimationListener() {		
			public void onAnimationStart(Animation animation) {
			}
			
			public void onAnimationRepeat(Animation animation) {
			}
			
			public void onAnimationEnd(Animation animation) {
				isPaletteOpen = false;
			}
		});
	}
	
	private void hidePalette(){
		Animation a = AnimationUtils.loadAnimation(this, R.anim.shrink);
		a.setStartOffset(0);
		mPaletteContainer.startAnimation(a);
		a.setAnimationListener(new AnimationListener() {		
			public void onAnimationStart(Animation animation) {
			}
			
			public void onAnimationRepeat(Animation animation) {
			}
			
			public void onAnimationEnd(Animation animation) {
				isPaletteOpen = false;
			}
		});
	}
	
	private void openPalette(){
		isPaletteOpen = true;
		Animation a = AnimationUtils.loadAnimation(this, R.anim.expand);
		mPaletteContainer.startAnimation(a);
		closePalette();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		
		mUndo = menu.add("Undo");
		mUndo.setIcon(R.drawable.menu_undo);
		mUndo.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				mImage.undo();
				if (mImage.isClean()){
					mUndo.setEnabled(false);
					mClear.setEnabled(false);
				}
				return false;
			}
		});
		
		mClear = menu.add("Clear");
		mClear.setIcon(R.drawable.menu_delete);
		mClear.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				mImage.clear();
				mUndo.setEnabled(false);
				mClear.setEnabled(false);
				return false;
			}
		});
		
		mShowPalette = menu.add("Show palette");
		mShowPalette.setIcon(R.drawable.menu_palette);
		mShowPalette.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				openPalette();
				return false;
			}
		});
		
		
		if (mImage.isClean()){
			mUndo.setEnabled(false);
			mClear.setEnabled(false);
		}
		
		
		return true;
	}
	
	private void saveImage(){
		//original bitmap
		Bitmap bmp = BitmapFactory.decodeFile(mPhoto.getPath());
		Log.d("MPM", "bmp.w="+bmp.getWidth()+", bmp.h="+bmp.getHeight());
		Rect r = getBitmapRect();
		Log.d("MPM", "r.w="+r.width()+", r.h="+r.height());
		Bitmap res = mImage.drawOriginalBitmap(bmp, (float)bmp.getHeight()/r.height(), r.left, r.top);

		try {
			mFSController.savePicture(res, mPhoto.getPath());
		} catch (SDNotReadyException e) {
			GuiController.showError(this, e.getMessage());
		}
		res.recycle(); 
		bmp.recycle();
	}

}
